package userController

import (
	"context"
	userApi "dev-assistant-backend/api/user"
	userDao "dev-assistant-backend/internal/dao/user"
	userService "dev-assistant-backend/internal/service/user"
	"dev-assistant-backend/utility/codemsg"
	"errors"
	"time"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/guid"
)

type Controller struct{}

// Create 创建用户
func (c *Controller) Create(ctx context.Context, req *userApi.CreateReq) (res *userApi.CreateRes, err error) {
	g.Log().Info(ctx, "create user", "req", req)

	userEntity := userDao.NewEntity(
		"ur"+guid.S(),
		req.Name,
		req.Email,
		req.Phone,
		req.Password,
		req.Role,
		userDao.StatusNormal,
	)

	user, err := userService.Create(ctx, userEntity)
	if err != nil {
		return nil, err
	}

	g.Log().Line(true).Info(ctx, "create user success", "user", user)

	request := g.RequestFromCtx(ctx)
	if request == nil {
		g.Log().Line(true).Error(ctx, "request is nil")
		return nil, codemsg.InternalServerErr
	}

	return userApi.NewCreateRes(
		user.Id,
		user.Name,
		user.Email,
		user.Phone,
		user.Role,
		user.Status,
	), nil
}

//////////////////////////////////////////////////////////

func (c *Controller) Login(ctx context.Context, req *userApi.LoginReq) (res *userApi.LoginRes, err error) {
	g.Log().Info(ctx, "login user", "req", req)

	user, jwt, err := userService.Login(ctx, req.Email, req.Password)
	if err != nil {
		if errors.Is(err, codemsg.UserNotFoundErr) {
			g.Log().Line(true).Info(ctx, "user not found", "email", req.Email)
			return nil, codemsg.UserNotFoundErr
		}
		if errors.Is(err, codemsg.PasswordIncorrectErr) {
			g.Log().Line(true).Info(ctx, "password incorrect", "email", req.Email)
			return nil, codemsg.PasswordIncorrectErr
		}
		if errors.Is(err, codemsg.UserBannedErr) {
			g.Log().Line(true).Info(ctx, "user banned", "email", req.Email)
			return nil, codemsg.UserBannedErr
		}
		if errors.Is(err, codemsg.UserDeletedErr) {
			g.Log().Line(true).Info(ctx, "user deleted", "email", req.Email)
			return nil, codemsg.UserDeletedErr
		}
		if errors.Is(err, codemsg.UserStatusInvalidErr) {
			g.Log().Line(true).Info(ctx, "user status invalid", "email", req.Email)
			return nil, codemsg.UserStatusInvalidErr
		}
		g.Log().Line(true).Error(ctx, "login user error", "error", err)
		return nil, err
	}

	request := g.RequestFromCtx(ctx)
	if request == nil {
		g.Log().Line(true).Error(ctx, "request is nil")
		return nil, codemsg.InternalServerErr
	}

	// 设置Cookie，7天过期时间
	request.Cookie.SetCookie("token", jwt, "", "/", 7*24*time.Hour)

	return userApi.NewLoginRes(
		user.Id,
		user.Name,
		user.Email,
		user.Phone,
		user.Role,
		user.Status,
	), nil
}
